﻿using System;
using System.Collections.Generic;
using ETModel;
using UnityEngine;
using UnityEngine.UI;

namespace ETHotfix
{
	[ObjectSystem]
	public class UIComponentAwakeSystem : AwakeSystem<UIComponent>
	{
		public override void Awake(UIComponent self)
		{
			self.Camera = Component.Global.transform.Find("UICamera").gameObject;
		}
	}
	
	/// <summary>
	/// 管理所有UI实体
	/// </summary>
	public class UIComponent: Component
	{
		//参考分辨率
		public Vector2 Resolution = new Vector2(640, 1280);
		//同一个UILayer的界面相差的order
		public const int MaxOderPerWindow = 10;
		//UILayer界面层级字典
		public Dictionary<string, int> layerOrderDic = new Dictionary<string, int>();

		public GameObject Camera;
		
		public Dictionary<string, UI> uis = new Dictionary<string, UI>();

		public void Add(UI ui,UILayer layer)
		{
			if (layerOrderDic.ContainsKey(layer.name))
			{
				layerOrderDic[layer.name] += MaxOderPerWindow;
			}
			else
			{
				layerOrderDic[layer.name] = layer.orderInLayer;
			}

			Canvas uiCanvas = ui.GameObject.GetComponent<Canvas>();
			uiCanvas.worldCamera = this.Camera.GetComponent<Camera>();
			uiCanvas.planeDistance = layer.planeDistance;
			uiCanvas.overrideSorting = true;
			uiCanvas.sortingOrder = layerOrderDic[layer.name];
			CanvasScaler uiCanvasScaler = ui.GameObject.GetComponent<CanvasScaler>();
			//	uiCanvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
			//	uiCanvasScaler.screenMatchMode = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
			uiCanvasScaler.referenceResolution = Resolution;

			this.uis.Add(ui.Name, ui);
			ui.Parent = this;
		}

		public void Remove(string name, UILayer layer)
		{
			if (!this.uis.TryGetValue(name, out UI ui))
			{
				return;
			}
			layerOrderDic[layer.name] -= MaxOderPerWindow;
			this.uis.Remove(name);
			ui.Dispose();
		}
		
		public UI Get(string name)
		{
			UI ui = null;
			this.uis.TryGetValue(name, out ui);
			return ui;
		}
	}
}